package com.bxait.toymail.seckill.interceptor;

import com.bxait.com.constant.AuthServerConstant;
import com.bxait.com.vo.member.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
@description:  秒杀服务中的拦截器
@ClassName LoginUserInterceptor
@author Chen
@create 2023-04-30 9:38
@Version 1.0
*/
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    /*
     * @param request
     * @param response
     * @param handler
     * @==============History===============<br/>
     * @Description //   目标方法执行之前,我们秒杀服务中的接口必须要求所以的请求接口都是登录状态下才能访问
     * @Date 2023/4/30 2023/4/30
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 匹配请求中是否包含需要登录才能放行的接口
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", uri);

        if(match){
            // 获取当前登录的用户
            MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
            if(attribute != null){
                loginUser.set(attribute);
                return true;
            }else {
                // 没登录就去登录
                request.getSession().setAttribute("msg","请先进行登录");
                response.sendRedirect("http://auth.toymail.com/login.html");
                return false;
            }
        }
        return true;
    }
}
